<?php
// +----------------------------------------------------------------------
// | thinkcmf [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +---------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace cmf\lib\taglib;

use think\template\TagLib;
use think\View;

class Cmf extends TagLib
{
    /**
     * 定义标签列表
     */
    protected $tags = [
        // 标签定义： attr 属性列表 close 是否闭合（0 或者1 默认1） alias 标签别名 level 嵌套层次
        'page'                => ['attr' => '', 'close' => 0],//非必须属性name
        'widget'              => ['attr' => 'name', 'close' => 1],
        'navigation'          => ['attr' => '', 'close' => 1],//非必须属性nav-id,root,id,class
        'navigationmenu'      => ['attr' => '', 'close' => 1],//root,class
        'navigationfolder'    => ['attr' => '', 'close' => 1],//root,class,dropdown,dropdown-class
        'subnavigation'       => ['attr' => 'parent,root,id,class', 'close' => 1],
        'subnavigationmenu'   => ['attr' => '', 'close' => 1],//root,class
        'subnavigationfolder' => ['attr' => '', 'close' => 1],//root,class,dropdown,dropdown-class
        'links'               => ['attr' => '', 'close' => 1],//非必须属性item
        'slides'              => ['attr' => 'id', 'close' => 1],//非必须属性item
        'noslides'            => ['attr' => 'id', 'close' => 1],
        'captcha'             => ['attr' => 'height,width,code_set', 'close' => 0],//非必须属性font-size,length,bg,id
        'hook'                => ['attr' => 'name,param', 'close' => 0],
		'imagetpl'            => ['attr'=>'id,name,value','close'=>0],
		'filetpl'             => ['attr'=>'id,name,value,type','close'=>0],
		'albumtpl'            => ['attr'=>'id,name,value','close'=>0],
		'ueditortpl'          => ['attr'=>'id,name,value,more','close'=>0],
		/*'selecttpl'           => ['attr'=>'id,name,value,type,style,class,pid','close'=>0],
		'checkboxtpl'         => ['attr'=>'id,name,value,type,style,class','close'=>0],
		'radiotpl'            => ['attr'=>'id,name,value,type,style,class','close'=>0],
    	'taxonomystpl'        => ['attr'=>'id,name,value,type,style,class,more,data','close'=>0]*/
    ];

    /**
     * 分页标签
     */
    public function tagPage($tag, $content)
    {

        $name = isset($tag['name']) ? $tag['name'] : '__PAGE_VAR_NAME__';
        $this->autoBuildVar($name);

        $parse = <<<parse
<?php
     echo empty({$name})?'':{$name};
 ?>
parse;

        return $parse;

    }

    /**
     * 组件标签
     */
    public function tagWidget($tag, $content)
    {

        if (empty($tag['name'])) {
            return '';
        }

        $name = $tag['name'];

        if (strpos($name, '$') === 0) {
            $this->autoBuildVar($name);
        } else {
            $name = "'{$name}'";
        }

        $parse = <<<parse
<?php
     if(isset(\$theme_widgets[{$name}]) && \$theme_widgets[{$name}]['display']){
        \$widget=\$theme_widgets[{$name}];
     
 ?>
{$content}
<?php
    }
 ?>


parse;

        return $parse;

    }

    /**
     * 导航标签
     */
    public function tagNavigation($tag, $content)
    {

        // nav-id,id,root,class
        $navId                   = isset($tag['nav-id']) ? $tag['nav-id'] : 0;
        $id                      = isset($tag['id']) ? $tag['id'] : '';
        $root                    = isset($tag['root']) ? $tag['root'] : 'ul';
        $class                   = isset($tag['class']) ? $tag['class'] : 'nav navbar-nav';
        $maxLevel                = isset($tag['max-level']) ? intval($tag['max-level']) : 0;
        $parseNavigationFuncName = '__parse_navigation' . md5(uniqid('_nav' . $navId . __LINE__, true));

        if (strpos($navId, '$') === 0) {
            $this->autoBuildVar($name);
        } else {
            $navId = "'{$navId}'";
        }

        $parse = <<<parse
<?php

function {$parseNavigationFuncName}(\$menus,\$level=1){
\$_parse_navigation_func_name = '{$parseNavigationFuncName}';
?>
    <foreach name="menus" item="menu">
    {$content}
    </foreach>
<?php 
}
?>

<?php
    \$navMenuModel = new \app\admin\model\NavMenuModel();
    \$menus = \$navMenuModel->navMenusTreeArray({$navId},{$maxLevel});
?>
<if condition="'{$root}'==''">
    {:{$parseNavigationFuncName}(\$menus)}
<else/>
    <{$root} id="{$id}" class="{$class}">
        {:{$parseNavigationFuncName}(\$menus)}
    </$root>
</if>

parse;
        return $parse;
    }

    /**
     * 导航menu标签
     */
    public function tagNavigationMenu($tag, $content)
    {
        //root,class
        $root  = !empty($tag['root']) ? $tag['root'] : 'li';
        $class = !empty($tag['class']) ? $tag['class'] : '';

        $parse = <<<parse
<if condition="empty(\$menu['children'])">
    <{$root} class="{$class}">
    {$content}
    </{$root}>
</if>
parse;
        return $parse;
    }

    /**
     * 导航folder标签
     */
    public function tagNavigationFolder($tag, $content)
    {
        //root,class,dropdown,dropdown-class
        $root          = isset($tag['root']) ? $tag['root'] : 'li';
        $class         = isset($tag['class']) ? $tag['class'] : 'dropdown';
        $dropdown      = isset($tag['dropdown']) ? $tag['dropdown'] : 'ul';
        $dropdownClass = isset($tag['dropdown-class']) ? $tag['dropdown-class'] : 'dropdown-menu';

        $parse = <<<parse
<if condition="!empty(\$menu['children'])">
    <{$root} class="{$class}">
        {$content}
        <{$dropdown} class="{$dropdownClass}">
            <php>
            \$mLevel=\$level+1;
            </php>
            <php>echo \$_parse_navigation_func_name(\$menu['children'],\$mLevel);</php>
        </{$dropdown}>
    </{$root}>
</if>
parse;
        return $parse;
    }

    /**
     * 子导航标签
     */
    public function tagSubNavigation($tag, $content)
    {

        // parent,id,root,class
        $parent                     = isset($tag['parent']) ? $tag['parent'] : 0;
        $id                         = isset($tag['id']) ? $tag['id'] : '';
        $root                       = isset($tag['root']) ? $tag['root'] : 'ul';
        $class                      = isset($tag['class']) ? $tag['class'] : 'nav navbar-nav';
        $maxLevel                   = isset($tag['max-level']) ? intval($tag['max-level']) : 0;
        $parseSubNavigationFuncName = '__parse_sub_navigation' . md5(uniqid('_nav' . $parent . $id . __LINE__, true));;

        if (strpos($parent, '$') === 0) {
            $this->autoBuildVar($name);
        } else {
            $parent = "'{$parent}'";
        }

        $parse = <<<parse
<?php
function {$parseSubNavigationFuncName}(\$menus,\$level=1){
\$_parse_sub_navigation_func_name = '{$parseSubNavigationFuncName}';
?>
    <foreach name="menus" item="menu">
    {$content}
    </foreach>
<?php 
}
?>

<?php
    \$navMenuModel = new \app\admin\model\NavMenuModel();
    \$menus = \$navMenuModel->subNavMenusTreeArray({$parent},{$maxLevel});
?>
<if condition="'{$root}'==''">
    {:{$parseSubNavigationFuncName}(\$menus)}
<else/>
    <{$root} id="{$id}" class="{$class}">
        {:{$parseSubNavigationFuncName}(\$menus)}
    </$root>
</if>

parse;
        return $parse;
    }

    /**
     * 子导航menu标签
     */
    public function tagSubNavigationMenu($tag, $content)
    {
        //root,class
        $root  = !empty($tag['root']) ? $tag['root'] : 'li';
        $class = !empty($tag['class']) ? $tag['class'] : '';

        $parse = <<<parse
<if condition="empty(\$menu['children'])">
    <{$root} class="{$class}">
    {$content}
    </{$root}>
</if>
parse;
        return $parse;
    }

    /**
     * 子导航folder标签
     */
    public function tagSubNavigationFolder($tag, $content)
    {
        //root,class,dropdown,dropdown-class
        $root          = isset($tag['root']) ? $tag['root'] : 'li';
        $class         = isset($tag['class']) ? $tag['class'] : 'dropdown';
        $dropdown      = isset($tag['dropdown']) ? $tag['dropdown'] : 'dropdown';
        $dropdownClass = isset($tag['dropdown-class']) ? $tag['dropdown-class'] : 'dropdown-menu';

        $parse = <<<parse
<if condition="!empty(\$menu['children'])">
    <{$root} class="{$class}">
        {$content}
        <{$dropdown} class="{$dropdownClass}">
            <php>\$mLevel=\$level+1;</php>
            <php>echo \$_parse_sub_navigation_func_name(\$menu['children'],\$mLevel);</php>
        </{$dropdown}>
    </{$root}>
</if>
parse;
        return $parse;
    }

    /**
     * 友情链接标签
     */
    public function tagLinks($tag, $content)
    {
        $item  = empty($tag['item']) ? 'vo' : $tag['item'];//循环变量名
        $parse = <<<parse
<?php
     \$__LINKS__ = \app\admin\service\ApiService::links();
?>
<volist name="__LINKS__" id="{$item}">
{$content}
</volist>
parse;

        return $parse;

    }

    /**
     * 幻灯片标签
     */
    public function tagSlides($tag, $content)
    {
        $id    = empty($tag['id']) ? '0' : $tag['id'];
        $item  = empty($tag['item']) ? 'vo' : $tag['item'];//循环变量名
        $parse = <<<parse
<?php
     \$__SLIDE_ITEMS__ = \app\admin\service\ApiService::slides({$id});
?>
<volist name="__SLIDE_ITEMS__" id="{$item}">
{$content}
</volist>
parse;

        return $parse;

    }

    /**
     * 无幻灯片标签
     */
    public function tagNoSlides($tag, $content)
    {
        $id    = empty($tag['id']) ? '0' : $tag['id'];
        $parse = <<<parse
<?php
    if(!isset(\$__SLIDE_ITEMS__)){
        \$__SLIDE_ITEMS__ = \app\admin\service\ApiService::slides({$id});
    }
?>
<if condition="count(\$__SLIDE_ITEMS__) eq 0">
{$content}
</if>
parse;

        return $parse;

    }

    public function tagCaptcha($tag, $content)
    {
        //height,width,font-size,length,bg,id
        $id       = empty($tag['id']) ? '' : '&id=' . $tag['id'];
        $height   = empty($tag['height']) ? '' : '&height=' . $tag['height'];
        $width    = empty($tag['width']) ? '' : '&width=' . $tag['width'];
        $fontSize = empty($tag['font-size']) ? '' : '&font_size=' . $tag['font-size'];
        $length   = empty($tag['length']) ? '' : '&length=' . $tag['length'];
        $bg       = empty($tag['bg']) ? '' : '&bg=' . $tag['bg'];
        $codeSet  = empty($tag['code_set']) ? '' : '&code_set=' . $tag['code_set'];
        $title    = empty($tag['title']) ? '换一张' : $tag['title'];
        $style    = empty($tag['style']) ? 'cursor: pointer;' : $tag['style'];
        $params   = ltrim("{$id}{$height}{$width}{$fontSize}{$length}{$bg}{$codeSet}", '&');
        $parse    = <<<parse
<php>\$__CAPTCHA_SRC=url('/captcha/new').'?{$params}';</php>
<img src="{\$__CAPTCHA_SRC}" onclick="this.src='{\$__CAPTCHA_SRC}&time='+Math.random();" title="{$title}" class="captcha captcha-img verify_img" style="{$style}"/>{$content}
parse;
        return $parse;
    }

    public function tagHook($tag, $content)
    {
        $name  = empty($tag['name']) ? '' : $tag['name'];
        $param = empty($tag['param']) ? '' : $tag['param'];
        $extra = empty($tag['extra']) ? '' : $tag['extra'];
        $once  = empty($tag['once']) ? 'false' : 'true';

        if (empty($param)) {
            $param = '$temp' . uniqid();
        } else if (strpos($param, '$') === false) {
            $this->autoBuildVar($param);
        }

        if (empty($extra)) {
            $extra = "null";
        } else if (strpos($extra, '$') === false) {
            $this->autoBuildVar($extra);
        }


        $parse = <<<parse
<php>
    \\think\\Hook::listen('{$name}',{$param},{$extra},{$once});
</php>
parse;
        return $parse;
    }

    public function tagImagetpl($tag, $content)
    {
        $id     =	empty($tag['id']) ? '' : $tag['id'];
        $name   =	empty($tag['name']) ? '' : $tag['name'];
        $value  =	empty($tag['value']) ? '' : $tag['value'];
        
        if(!empty($value)){
            $parse    = <<<parse
            <php>\${$id}ImageValue = {$value};</php>
parse;
        }
        else{
            $parse    = <<<parse
            <php>\${$id}ImageValue = null;</php>
parse;
        }
        
        $parse    .= <<<parse
        
<input type="hidden" name="{$name}" id="{$id}" value="<?php echo \${$id}ImageValue; ?>">
<a href="javascript:uploadOneImage('图片上传','#{$id}');">
    <if condition="empty(\${$id}ImageValue)">
        <img src="__TMPL__/public/assets/images/default-thumbnail.png"
             id="{$id}-preview" width="135" style="cursor: hand"/>
    <else/>
        <img src="{:cmf_get_image_url(\${$id}ImageValue)}" id="{$id}-preview"
             width="135" style="cursor: hand"/>
    </if>
</a>
<input type="button" class="btn btn-default btn-sm"
       onclick="$('#{$id}-preview').attr('src','__TMPL__/public/assets/images/default-thumbnail.png');$('#{$id}').val('');return false;"
       value="取消图片">
        
parse;

        return $parse;
    }
    
    public function tagFiletpl($tag, $content)
    {
        $id     =	empty($tag['id']) ? '' : $tag['id'];
        $name   =	empty($tag['name']) ? '' : $tag['name'];
        $value  =	empty($tag['value']) ? '' : $tag['value'];
        $type  =	empty($tag['type']) ? 'file' : $tag['type'];
        
        if(!empty($value)){
            $parse    = <<<parse
            <php>\${$id}FileValue = {$value};</php>
parse;
        }
        else{
            $parse    = <<<parse
            <php>\${$id}FileValue = null;</php>
parse;
        }
        
        $parse    .= <<<parse
<table border="0">
	<tr>
		<td width="20">
            <input type="hidden" name="{$name}" id="{$id}" value="<?php echo \${$id}FileValue; ?>">
            <a href="<empty name="\${$id}FileValue">javascript:;<else/><?php echo \${$id}FileValue; ?></empty>" id="{$id}-url">
            	<img id="{$id}-preview" style="height:16px;width: 16px;"
            	   src="{:cmf_get_asset_icon(\${$id}FileValue)}">
            </a>
        </td>
        <td width="205">
            <input class="form-control input-sm" style="width:200px;" type="text" id="{$id}-name"
             value="{:sp_get_asset_field(\${$id}FileValue,'filename')}" disabled="disabled">
        </td>
        <td>
            <input type="button" class="btn btn-default btn-sm" id="{$id}-upload" value="<empty name="\${$id}FileValue">上传文件<else/>取消文件</empty>">
       </td>
</table>
<script>
$("#{$id}-upload").click(function(){
	if($(this).val()=='取消文件'){
		$('#{$id}').val('');
		$('#{$id}-name').val('');
		$('#{$id}-url').attr('href','javascript:;');
		$('#{$id}-preview').attr('src','{:cmf_get_asset_icon()}');
		$(this).val('上传文件');
	}
	else{
		uploadOneFile('文件上传','#{$id}','{$type}');
		$(this).val('取消文件');
	}
            
	return false;
})
</script>
            
parse;

        return $parse;
    }
    
    public function tagAlbumtpl($tag, $content){
        $id     =	empty($tag['id']) ? '' : $tag['id'];
        $name   =	empty($tag['name']) ? '' : $tag['name'];
        $value  =	empty($tag['value']) ? '' : $tag['value'];
        
        $parse    = <<<parse
        
<script type="text/html" id="{$id}s-item-tpl">
    <li id="saved-image-{$id}{id}">
        <input id="{$id}-{id}" type="hidden" name="{$id}_attrs[{id}][url]" value="{filepath}">
        <input class="form-control" id="{$id}-{id}-name" type="text" name="{$id}_attrs[{id}][name]" value="{name}"
               style="width: 200px;" title="图片名称">
        <img id="{$id}-{id}-preview" src="{url}" style="height:36px;width: 36px;"
             onclick="imagePreviewDialog(this.src);">
        <a href="javascript:uploadOneImage('图片上传','#{$id}-{id}');">替换</a>
        <a href="javascript:$('#saved-image-{$id}{id}').remove();">移除</a>
    </li>
</script>

<input type="hidden" name="auto_album_save[]" value="{$id}">
<ul id="{$id}s" class="pic-list list-unstyled form-inline">

parse;
        
        if(!empty($value)){
            $parse    .= <<<parse
            
    <php>\${$id}list = json_decode(htmlspecialchars_decode($value),true);</php>
    <notempty name="\${$id}list">
        <foreach name="\${$id}list" item="vo">
            <php>\$img_url=cmf_get_image_preview_url(\$vo['url']);</php>
            <li id="saved-image-{$id}{\$key}">
                <input id="{$id}-{\$key}" type="hidden" name="{$id}_attrs[{\$key}][url]"
                       value="{\$vo['url']}">
                <input class="form-control" id="{$id}-{\$key}-name" type="text"
                       name="{$id}_attrs[{\$key}][name]"
                       value="{\$vo['name']}" style="width: 200px;" title="图片名称">
                <img id="{$id}-{\$key}-preview"
                     src="{:cmf_get_image_preview_url(\$vo['url'])}"
                     style="height:36px;width: 36px;"
                     onclick="parent.imagePreviewDialog(this.src);">
                <a href="javascript:uploadOneImage('图片上传','#{$id}-{\$key}');">替换</a>
                <a href="javascript:$('#saved-image-{$id}{\$key}').remove();">移除</a>
            </li>
        </foreach>
    </notempty>
            
parse;
        }
        
        $parse    .= <<<parse

</ul>
<a href="javascript:uploadMultiImage('图片上传','#{$id}s','{$id}s-item-tpl');"
   class="btn btn-sm btn-default">选择图片</a>
    
parse;
        
        return $parse;
    }
    
    public function tagUeditortpl($tag, $content){
        
        $id     =	empty($tag['id']) ? '' : $tag['id'];
        $name   =	empty($tag['name']) ? '' : $tag['name'];
        $value  =	empty($tag['value']) ? '' : $tag['value'];
        $more	=	empty($tag['more'])?false:true;
        
        if(!empty($value)){
            $parse    = <<<parse
            <php>\${$id}UeditorValue = {$value};</php>
parse;
        }
        else{
            $parse    = <<<parse
            <php>\${$id}UeditorValue = null;</php>
parse;
        }
        
        if(!$more){
            $parse    .= <<<parse
<script type="text/javascript" src="__STATIC__/js/ueditor/ueditor.config.js"></script>
<script type="text/javascript" src="__STATIC__/js/ueditor/ueditor.all.min.js"></script>
parse;
        }
        
        $parse    .= <<<parse
        
<textarea type="text/plain" id="{$id}" name="{$name}" style="height: 200px;resize:vertical;"><?php echo \${$id}UeditorValue; ?></textarea>
<script>
$(function() {
	var editor_{$id} = UE.getEditor('{$id}',{
	    autoHeight: false,
		initialFrameHeight:200,//设置编辑器高度
		initialFrameWidth:'100%',
		scaleEnabled:true
	});
})
</script>
        
parse;
        return $parse;
    }
    
    
}